package com.ms.web.config;

import com.ms.common.utils.EnvUtil;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

@Configuration
@Slf4j
public class ImportantBeanPostProcessor implements BeanFactoryAware, InstantiationAwareBeanPostProcessor {

    private ConfigurableListableBeanFactory beanFactory;

    @Override
    public void setBeanFactory(@Nullable BeanFactory beanFactory) {
        if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
            throw new IllegalArgumentException("AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
        }
        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }

    private void createImportantBean() {
        beanFactory.getBean(EnvUtil.class);
    }

    @Override
    public boolean postProcessAfterInstantiation(@Nullable Object bean, @Nullable String beanName) throws BeansException {
        boolean annotationPresent = Objects.requireNonNull(bean).getClass().isAnnotationPresent(SpringBootApplication.class);
        if (annotationPresent) {
            log.info("加载重要的bean");
            createImportantBean();
        }
        return true;
    }

}
